package com.pkk.penguin.frame.know.java.jvm.classload;

import java.io.FileNotFoundException;

/**
 * @description: 用户自定义加载器
 * @author: peikunkun
 * @create: 2020-02-20 14:29
 **/
public class CustomerClassLoader extends ClassLoader {

  /**
   * Finds the class with the specified <a href="#name">binary name</a>. This method should be overridden by class
   * loader implementations that follow the delegation model for loading classes, and will be invoked by the {@link
   * #loadClass <tt>loadClass</tt>} method after checking the parent class loader for the requested class.  The default
   * implementation throws a <tt>ClassNotFoundException</tt>.
   *
   * @param name The <a href="#name">binary name</a> of the class
   * @return The resulting <tt>Class</tt> object
   * @throws ClassNotFoundException If the class could not be found
   * @since 1.2
   */
  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    System.out.println("定义用户自定义加载器,如果不要那么细的精确操作,也可以直接继承URLClassLoader,也不用自己去获取类的字节码数组了");
    byte[] result = getClassFromCustomPath(name);
    try {
      if (null == result) {
        throw new FileNotFoundException();
      } else {
        //此处要配合findClass一起使用
        return defineClass(name, result, 0, result.length);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    throw new ClassNotFoundException();
  }

  private byte[] getClassFromCustomPath(String name) {
    //从自定义的路径加载指定的类

    //同时也可以在此做源代码的加密操作
    return null;
  }
}
